package config

import (
	"encoding/json"
	"fmt"
	"os"
)

// Config represents the application configuration
type Config struct {
	Server  ServerConfig  `json:"server"`
	UKey    UKeyConfig    `json:"ukey"`
	Auth    AuthConfig    `json:"auth"`
	Webhook WebhookConfig `json:"webhook"`
	Log     LogConfig     `json:"log"`
}

// ServerConfig represents HTTP server configuration
type ServerConfig struct {
	Port string `json:"port"`
}

// UKeyConfig represents UKey WebSocket configuration
type UKeyConfig struct {
	URL      string `json:"url"`
	Password string `json:"password"`
}

// AuthConfig represents authentication configuration
type AuthConfig struct {
	AppSecret string `json:"app_secret"`
}

// WebhookConfig represents webhook notification configuration
type WebhookConfig struct {
	FailureURL string `json:"failure_url"` // For UKey malfunction notifications
	AuditURL   string `json:"audit_url"`   // For auditing all requests/responses
}

// LogConfig represents logging configuration
type LogConfig struct {
	Verbose bool `json:"verbose"`
}

// ParsedConfig represents the parsed configuration with time.Duration values
type ParsedConfig struct {
	Server  ParsedServerConfig
	UKey    ParsedUKeyConfig
	Auth    AuthConfig
	Webhook WebhookConfig
	Log     LogConfig
}

// ParsedServerConfig represents parsed server configuration
type ParsedServerConfig struct {
	Port string
}

// ParsedUKeyConfig represents parsed UKey configuration
type ParsedUKeyConfig struct {
	URL      string
	Password string
}

// LoadConfig loads configuration from a JSON file
func LoadConfig(path string) (*ParsedConfig, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("failed to open config file: %w", err)
	}
	defer file.Close()

	var cfg Config
	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&cfg); err != nil {
		return nil, fmt.Errorf("failed to decode config file: %w", err)
	}

	// Parse configuration with defaults
	parsed := &ParsedConfig{
		Auth:    cfg.Auth,
		Webhook: cfg.Webhook,
		Log:     cfg.Log,
	}

	// Parse server config
	parsed.Server.Port = cfg.Server.Port
	if parsed.Server.Port == "" {
		parsed.Server.Port = "8780"
	}

	// Parse UKey config
	parsed.UKey.URL = cfg.UKey.URL
	if parsed.UKey.URL == "" {
		parsed.UKey.URL = "ws://127.0.0.1:61232"
	}

	parsed.UKey.Password = cfg.UKey.Password
	if parsed.UKey.Password == "" {
		parsed.UKey.Password = "88888888"
	}

	return parsed, nil
}
